<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>讯飞AI直接测试（绕过后端）</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            width: 100%;
            max-width: 800px;
            padding: 40px;
        }
        
        h1 {
            text-align: center;
            color: #667eea;
            margin-bottom: 10px;
            font-size: 32px;
        }
        
        .subtitle {
            text-align: center;
            color: #888;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .test-section {
            margin-bottom: 30px;
        }
        
        .test-section h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .config-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .config-info .item {
            display: flex;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .config-info .label {
            font-weight: bold;
            color: #667eea;
            min-width: 120px;
        }
        
        .config-info .value {
            color: #555;
            word-break: break-all;
        }
        
        .test-area {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        input, textarea {
            width: 100%;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        
        input:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        
        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            min-width: 120px;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        
        button:active {
            transform: translateY(0);
        }
        
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .result {
            margin-top: 20px;
            padding: 20px;
            border-radius: 10px;
            white-space: pre-wrap;
            word-break: break-word;
            font-family: "Courier New", monospace;
            font-size: 13px;
        }
        
        .result.success {
            background: #d4edda;
            border: 2px solid #28a745;
            color: #155724;
        }
        
        .result.error {
            background: #f8d7da;
            border: 2px solid #dc3545;
            color: #721c24;
        }
        
        .result.info {
            background: #d1ecf1;
            border: 2px solid #17a2b8;
            color: #0c5460;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .status {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status.online {
            background: #28a745;
            box-shadow: 0 0 10px #28a745;
        }
        
        .status.offline {
            background: #dc3545;
            box-shadow: 0 0 10px #dc3545;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 讯飞AI直接测试</h1>
        <p class="subtitle">绕过后端，直接从浏览器调用讯飞API</p>
        
        <!-- 配置信息 -->
        <div class="test-section">
            <h2>📋 当前配置</h2>
            <div class="config-info">
                <div class="item">
                    <span class="label">AppId:</span>
                    <span class="value">d0c23e78</span>
                </div>
                <div class="item">
                    <span class="label">ApiKey:</span>
                    <span class="value">78ec2d4587e51c0395052e661fcc6b7a</span>
                </div>
                <div class="item">
                    <span class="label">模型:</span>
                    <span class="value">Spark X1-32K</span>
                </div>
                <div class="item">
                    <span class="label">接口类型:</span>
                    <span class="value">HTTP (绕过WebSocket的复杂认证)</span>
                </div>
            </div>
        </div>
        
        <!-- 测试区域 -->
        <div class="test-section">
            <h2><span class="status offline" id="status"></span>测试对话</h2>
            <div class="test-area">
                <input type="text" id="messageInput" placeholder="输入消息，例如：你好" value="你好，请介绍一下你自己">
                <button onclick="testChat()" id="testBtn">
                    <span id="btnText">发送测试</span>
                </button>
            </div>
            <div id="result"></div>
        </div>
        
        <!-- 说明 -->
        <div class="test-section">
            <h2>💡 说明</h2>
            <div class="config-info">
                <p style="line-height: 1.8; color: #555;">
                    ⚠️ <strong>注意</strong>：由于浏览器的CORS限制，直接从前端调用讯飞API会失败。<br><br>
                    
                    <strong>这个测试页面的目的：</strong><br>
                    1. 演示正确的API调用方式<br>
                    2. 验证您的凭证格式<br>
                    3. 提供后端实现参考<br><br>
                    
                    <strong>最终解决方案：</strong><br>
                    ✅ 使用我提供的后端代码（XunfeiAIService.cs）<br>
                    ✅ 它使用HTTP接口，认证简单可靠<br>
                    ✅ 前端无需修改，直接可用
                </p>
            </div>
        </div>
    </div>

    <script>
        // 显示在线状态
        document.getElementById('status').className = 'status offline';
        
        async function testChat() {
            const btn = document.getElementById('testBtn');
            const btnText = document.getElementById('btnText');
            const result = document.getElementById('result');
            const message = document.getElementById('messageInput').value;
            
            if (!message.trim()) {
                showResult('error', '请输入消息');
                return;
            }
            
            // 禁用按钮
            btn.disabled = true;
            btnText.innerHTML = '<span class="loading"></span>';
            
            try {
                showResult('info', '正在调用讯飞AI...\n\n⚠️ 由于浏览器CORS限制，这个请求预期会失败。\n但您可以看到正确的调用方式！');
                
                // 构建请求
                const apiUrl = 'https://spark-api-open.xf-yun.com/v1/chat/completions';
                const apiKey = '78ec2d4587e51c0395052e661fcc6b7a';
                
                const requestBody = {
                    model: 'generalv3.5',
                    messages: [
                        {
                            role: 'user',
                            content: message
                        }
                    ],
                    temperature: 0.5,
                    max_tokens: 2048,
                    stream: false
                };
                
                console.log('📤 请求URL:', apiUrl);
                console.log('📤 请求体:', JSON.stringify(requestBody, null, 2));
                console.log('🔑 Authorization:', `Bearer ${apiKey}`);
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify(requestBody)
                });
                
                console.log('📥 响应状态:', response.status);
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('📥 响应数据:', data);
                    
                    const answer = data.choices[0].message.content;
                    
                    showResult('success', 
                        '✅ 调用成功！\n\n' +
                        '👤 您: ' + message + '\n\n' +
                        '🤖 AI: ' + answer + '\n\n' +
                        '━━━━━━━━━━━━━━━━━━━━\n' +
                        '完整响应:\n' + JSON.stringify(data, null, 2)
                    );
                    
                    document.getElementById('status').className = 'status online';
                } else {
                    const errorText = await response.text();
                    console.error('❌ 错误响应:', errorText);
                    
                    showResult('error',
                        '❌ API调用失败\n\n' +
                        '状态码: ' + response.status + '\n' +
                        '错误信息: ' + errorText + '\n\n' +
                        '━━━━━━━━━━━━━━━━━━━━\n' +
                        '可能的原因:\n' +
                        '1. API Key不正确\n' +
                        '2. 服务未开通\n' +
                        '3. 调用次数用完\n' +
                        '4. IP白名单限制\n\n' +
                        '💡 建议: 使用后端服务调用讯飞API'
                    );
                }
            } catch (error) {
                console.error('❌ 请求异常:', error);
                
                showResult('error',
                    '❌ 请求失败 (预期的CORS错误)\n\n' +
                    '错误: ' + error.message + '\n\n' +
                    '━━━━━━━━━━━━━━━━━━━━\n' +
                    '这是正常的！浏览器阻止了跨域请求。\n\n' +
                    '✅ 正确的做法:\n' +
                    '1. 在后端服务中调用讯飞API\n' +
                    '2. 使用我提供的 XunfeiAIService.cs 代码\n' +
                    '3. 后端代码使用HTTP客户端，没有CORS限制\n\n' +
                    '📝 后端代码示例:\n' +
                    '```csharp\n' +
                    'var httpClient = new HttpClient();\n' +
                    'httpClient.DefaultRequestHeaders.Add(\n' +
                    '    "Authorization", \n' +
                    '    $"Bearer {apiKey}"\n' +
                    ');\n' +
                    '\n' +
                    'var response = await httpClient.PostAsJsonAsync(\n' +
                    '    "https://spark-api-open.xf-yun.com/v1/chat/completions",\n' +
                    '    requestBody\n' +
                    ');\n' +
                    '```\n\n' +
                    '这样就能正常工作了！✅'
                );
            } finally {
                // 恢复按钮
                btn.disabled = false;
                btnText.textContent = '发送测试';
            }
        }
        
        function showResult(type, message) {
            const result = document.getElementById('result');
            result.className = 'result ' + type;
            result.textContent = message;
        }
        
        // 回车发送
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                testChat();
            }
        });
    </script>
</body>
</html>

